<template>
  <div>
    <input @change="fileChange($event)" type="file" ref="upload_file" multiple style="display: none"/>
    <div class="image-list flex-bt">
      <div class="upload-box" :style="{height: (boxHeight ? boxHeight:'')}" @tap="choosePic">
        <div class="upload-inner">
          <span class="mui-icon mui-icon-plusempty"></span>
        </div>
      </div>
      <div class="img-item" v-for="(item, index) in imgList" :key="index">
        <span class="ico-move" @tap="removePic(index)">-</span>
        <div class="pic-box" :style="{height: (boxHeight ? boxHeight:'')}">
          <img :src="item" alt="相片">
        </div>
      </div>
      <div class="img-item"></div>
      <div class="img-item"></div>
    </div>

    <div class="cropper-box" v-show='cropper'>
      <div class="cropper">
        <vueCropper
          ref="cropper"
          :img="option.img"
          :outputSize="option.size"
          :outputType="option.outputType"
          :canMove="option.canMove"
          :canMoveBox="option.canMoveBox"
          :original="option.original"
          :autoCrop="option.autoCrop"
          :autoCropWidth="option.autoCropWidth"
          :autoCropHeight="option.autoCropHeight"
          :fixedBox="option.fixedBox"
        ></vueCropper>
      </div>
      <div class="cropper-btn">
        <span @click='closeBtn'>取消</span>
        <span class="cur" @click='uploadImg'>确定</span>
      </div>
    </div>

  </div>
</template>

<script>
  import { VueCropper }  from 'vue-cropper';
  import {MH_API} from "@/api/api";
  export default {
    name: "mh-upload",
    data () {
      return {
        cropper: false,
        option: {
          img: '',
          size: 1,
          outputType: 'png',
          canMove: true, 
          original: false, 
          canMoveBox: true, 
          autoCrop: true, 
          autoCropWidth: 300, 
          autoCropHeight: 300, 
          fixedBox: true
        },
        boxHeight: '',
        size: 0,
        limit:6,
        imgList: [
          // {
          //   id: '1',
          //   imgSrc: 'https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1700510748,1888429117&fm=26&gp=0.jpg'
          // },
          // {
          //   id: '2',
          //   imgSrc: 'https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=2082925491,3690093855&fm=26&gp=0.jpg'
          // },
          // {
          //   id: '3',
          //   imgSrc: 'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3320410772,2527585586&fm=26&gp=0.jpg'
          // }
        ]
      }
    },
    mounted () {
      // console.log(document.getElementsByClassName('img-item')[0].clientWidth);
      this.boxHeight = document.getElementsByClassName('img-item')[0].clientWidth + 'px';
    },
    methods: {
      closeBtn(){
        this.cropper = false;
        this.fileName = '';
      },
      selectImg(e){
        console.log(e.target)
        let self = this;
        let file = e.target.files[0];
        let reader = new FileReader();
        let imgUrlBase64 = '';
        if (file) {
            //将文件以Data URL形式读入页面  
            imgUrlBase64 = reader.readAsDataURL(file);
            reader.onload = function (e) {
              console.log(reader.result)
              self.option.img = reader.result;
              self.cropper = true;
            }
        }
      },
      uploadImg:function(){
        this.cropper = false;
        let self = this;
        let formData = new FormData();
        this.$refs.cropper.getCropBlob((data) => {
          formData.append('file', data);
          formData.append('token', window.localStorage.getItem("uploadToken"));
          mui.toast('上传中');
          MH_API.uploadImg(formData).then(res => {
            if (res.key) {
              mui.toast('上传成功');
              self.imgList.push(MH_API.QN_url+res.key);
              this.$parent.getImages(self.imgList);
            }
          })
        })

      },
      fileChange(el) {
        if (!el.target.files[0].size) return;
        //this.fileList(el.target);
        //el.target.value = '';
        this.selectImg(el);
      },
      choosePic () {
        this.$refs.upload_file.click();
      },
      removePic (index) {
        let _this = this;
        let btnArray = ['取消', '确定'];
        mui.confirm('确认要删除照片吗？', '提示', btnArray, function(e) {
          // _this.size = _this.size - _this.imgList[index].file.size;//总大小
          if (e.index === 1) {
            _this.imgList.splice(index, 1);
            // if (_this.limit !== undefined) _this.limit = _this.limit - _this.imgList.length;
          } else {

          }
        })
      },
      fileList(fileList) {
        let files = fileList.files;
        for (let i = 0; i < files.length; i++) {
          //判断是否为文件夹
          if (files[i].type !== '') {
            this.fileAdd(files[i]);
          } else {
            //文件夹处理
            this.folders(fileList.items[i]);
          }
        }
      },
      //文件夹处理
      folders(files) {
        let _this = this;
        //判断是否为原生file
        if (files.kind) {
          files = files.webkitGetAsEntry();
        }
        files.createReader().readEntries(function (file) {
          for (let i = 0; i < file.length; i++) {
            if (file[i].isFile) {
              _this.foldersAdd(file[i]);
            } else {
              _this.folders(file[i]);
            }
          }
        });

      },
      foldersAdd(entry) {
        let _this = this;
        entry.file(function (file) {
          _this.fileAdd(file)
        })
      },
      fileAdd(file) {
        if (this.limit !== undefined) this.limit--;
        if (this.limit !== undefined && this.limit < 0) return;
        //总大小
        this.size = this.size + file.size;
        //判断是否为图片文件
        if (file.type.indexOf('image') === -1) {
          mui.toast('请选择图片文件');
        } else {
          let reader = new FileReader();
          let image = new Image();
          let _this = this;
          reader.readAsDataURL(file);
          reader.onload = function () {
            file.src = this.result;
            image.onload = function(){
              let width = image.width;
              let height = image.height;
              file.width = width;
              file.height = height;
              console.log(file);
              _this.imgList.push({
                imgSrc: file.src
              });
              console.log( _this.imgList);
            };
            image.src= file.src;
          }
        }
      }
    },
    components: {
      VueCropper
    }
  }
</script>

<style lang="scss" scoped>
  @import "../../assets/css/mixin";
  .cropper-box{ position:absolute; top:0; left:0; z-index:999; background-color:#000; width:100%; height:100%;}
  .cropper{ width:100%; height:50rem;}
  .cropper-btn{ display:flex; padding-top:2rem;justify-content:center;}
  .cropper-btn span{ display:inline-block; line-height:4rem; padding:0 2rem; border-radius:0.5rem; margin: 0 2rem; color:#fff; font-size:1.4rem; background-color:#a9a9a9;}
  .cropper-btn span.cur{ background-color:#e685aa;}

  .pic-box {
    @include mh-avatar-box(auto, 100%);
    border-radius: 0;
    background-color: #eee;
  }
  .upload-box {
    background-color: #eee;
    .upload-inner {
      padding: 2rem;
      @include center;
      text-align: center;
      background-color: #eee;
      overflow: hidden;
      span {@include sc(5rem, #dedede)}
    }
  }
  .img-item,.upload-box {
    position: relative;
    display: inline-block;
    width: 31%;
    height: 40%;
    margin: 0 auto .5rem;
  }
  .image-list {
    flex-wrap: wrap;
    width: 100%;
    height: 100%;
    padding: .5rem 1rem;
    background-color: #fff;
  }
  .ico-move {
    position: absolute;
    display: inline-block;
    width: 1.8rem;
    height: 1.8rem;
    line-height: 1.2rem;
    right: -.5rem;
    top: -.5rem;
    background-color: #fc5624;
    border-radius: 100%;
    text-align: center;
    @include sc(3rem, #fff);
  }
</style>
